package org.modified.gridview;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

//import org.modified.gridview.R;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

public class MyGridViewActivity extends Activity {
	public static final int BOOK_NUM = 12;
	int left_num = BOOK_NUM;
	int ordered = 0;
	private static final int TOTAL_TIME = 20;
	private static final int THRESHOLD = 4;
	private static int prePos = -1;
	private static int curPos = -1;
	private GridView gridview1;
	static View preView;
	static View curView;
	static Rect rect;
	static Canvas canvas = new Canvas();
	// Context context;
	private MyBookImageUtil imageUtil;
	List<MyBookImage> bookshelf = new ArrayList<MyBookImage>();
	// imageUtil.getPlayImages(imageUtil.mkContext(MyGridViewActivity.this.getApplicationContext()),BOOK_NUM);
	ArrayList<Integer> playBooksId;
	// private List<Integer> orderedBookId = new ArrayList<Integer>();
	// private List<Integer> unorderedBookId = new ArrayList<Integer>();
	private Button startButton;
	private TextView timeTextView;
	private Timer timer = new Timer();
	private int gameTime;
	boolean isPlaying = true;

	public ImageAdapter1 imageAdapter1;// 2011-11-30
	public ImageAdapter2 imageAdapter2;

	ArrayList<Integer> orderedBookId = new ArrayList<Integer>();
	ArrayList<Integer> unorderedBookId = new ArrayList<Integer>();

	Context getMyContext() {
		return MyGridViewActivity.this;
	}

	public static Bitmap getSelectImage(Context context) {
		Bitmap bm = BitmapFactory.decodeResource(context.getResources(),
				R.drawable.book_selected);
		return bm;
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 0x123) {
				timeTextView.setText("剩余时间： " + gameTime);
				gameTime--;
				if (gameTime < 0)// 时间到
				{
					stopTimer();
					// 更改游戏的状态
					isPlaying = false;
					return;
				}
			}
		}
	};

	private void stopTimer() {
		// 停止定时器
		this.timer.cancel();
		this.timer = null;
	}

	private void startGame(int gameTime) {
		// 如果之前的timer还未取消，取消timer
		if (this.timer != null) {
			stopTimer();
		}
		// 重新设置游戏时间
		this.gameTime = gameTime;
		// 如果游戏剩余时间与总游戏时间相等，即为重新开始新游戏
		isPlaying = true;
		this.timer = new Timer();
		// 启动计时器 ， 每隔1秒发送一次消息
		this.timer.schedule(new TimerTask() {
			public void run() {
				handler.sendEmptyMessage(0x123);
			}
		}, 0, 1000);
		// 将选中方块设为null。
		// this.selected = null;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_main);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

		initResource();
	}

	public void initResource() {
		imageUtil = new MyBookImageUtil(
				MyGridViewActivity.this.getApplicationContext());
		playBooksId = imageUtil.getPlayValues(BOOK_NUM);
		bookshelf = imageUtil.getPlayImages(imageUtil.getContext(), BOOK_NUM);
		gridview1 = (GridView) findViewById(R.id.gridView1);
		imageAdapter1 = new ImageAdapter1(this);// 2011-11-30
		gridview1.setAdapter(imageAdapter1);// 2011-11-30

		GridView gridview2 = (GridView) findViewById(R.id.gridView2);
		imageAdapter2 = new ImageAdapter2(this);
		gridview2.setAdapter(imageAdapter2);
		timeTextView = (TextView) findViewById(R.id.timeText);
		startButton = (Button) this.findViewById(R.id.startButton);

		gridview2.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (prePos == -1) {
					prePos = arg2;
					preView = arg1;
//					Log.i(String.valueOf(prePos), "prePos");
//					Log.i(String.valueOf(preView), "preView");
//					canvas.drawBitmap(MyGridViewActivity
//							.getSelectImage(MyGridViewActivity.this
//									.getApplicationContext()), (float) (preView
//							.getLeft()), (float) (preView.getTop()), null);
//					Bitmap bm = MyGridViewActivity
//							.getSelectImage(MyGridViewActivity.this
//									.getApplicationContext());
//					Log.i(String.valueOf(bm), "bm");
//					 rect = new
//					 Rect(preView.getLeft(),preView.getTop(),preView.getRight(),preView.getBottom());
//					 canvas.drawRect(rect, null);
				} else {
					curPos = arg2;
					curView = arg1;
					Log.i(String.valueOf(curPos), "curPos");
					Log.i(String.valueOf(curView), "curView");
					if (curView != preView) {
						imageUtil.exchangeBooks(curPos, prePos, unorderedBookId);
						imageAdapter2.notifyDataSetChanged();
						// 计算有序值ordered
						ordered = imageUtil.orderedNum(orderedBookId, unorderedBookId,THRESHOLD);
//						Log.i(String.valueOf(ordered),"ordered");
//						Integer id00 = orderedBookId.get(0);
//						Integer uid00 = unorderedBookId.get(0);
//						Log.i(String.valueOf(id00), "ordered0");
//						Log.i(String.valueOf(uid00), "unordered0");
//						Integer id01 = orderedBookId.get(1);
//						Integer uid01 = unorderedBookId.get(1);
//						Log.i(String.valueOf(id01), "ordered1");
//						Log.i(String.valueOf(uid01), "unordered1");
						
						if (ordered >= THRESHOLD && left_num != 0) {
							imageUtil.removeBooks(orderedBookId, unorderedBookId, THRESHOLD);
							imageAdapter1.notifyDataSetChanged();
							imageAdapter2.notifyDataSetChanged();
							ordered = 0;
							left_num -= THRESHOLD;
						}
						prePos = -1;
						curPos = -1;
					}
				}
			}
		});

		startButton.setOnClickListener(new View.OnClickListener() {
			// @Override
			public void onClick(View source) {
				// gridview1.postInvalidate();
				startGame(TOTAL_TIME);
				// 控制button,用于重新设置文本
				startButton.setText("重新开始");
			}
		});
	}

	public class ImageAdapter1 extends BaseAdapter {
		private Context mContext;

		// references to our images

		public ImageAdapter1(Context c) {
			mContext = c;
			for (int i = 0; i < BOOK_NUM; i++) {
//				orderedBookId.add(playBooksId.get(i));
				orderedBookId.add(bookshelf.get(i).getImageId());
			}
		}

		/**
		 * Count of items.
		 */
		public int getCount() {
			return orderedBookId.size();
		}

		/**
		 * Get the data item associated with the specified position in the data
		 * set.
		 */
		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		/*
		 * Get a View that displays the data at the specified position in the
		 * data set. You can either create a View manually or inflate it from an
		 * XML layout file. When the View is inflated, the parent View
		 * (GridView, ListView...) will apply default layout parameters unless
		 * you use inflate(int, android.view.ViewGroup, boolean) to specify a
		 * root view and to prevent attachment to the root.
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView;// 定义图片资源
			if (convertView == null) { // if it's not recycled, initialize some
										// attributes
				imageView = new ImageView(mContext);// 设定view的上下文
				imageView.setLayoutParams(new GridView.LayoutParams(31, 50));// 设定图片的大小
				imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);// 按比例扩大图片的size居中显示，使得图片长
																		// (宽)等于或大于View的长(宽)
				imageView.setPadding(4, 4, 4, 4);// 设置上下左右的padding值
			} else {
				imageView = (ImageView) convertView;
			}

			imageView.setImageResource(orderedBookId.get(position));
			return imageView;
		}
	}

	public class ImageAdapter2 extends BaseAdapter {
		private Context mContext;

		public ImageAdapter2(Context c) {
			mContext = c;
			for (int i = BOOK_NUM; i < 2 * BOOK_NUM; i++) {
//				unorderedBookId.add(playBooksId.get(i));
				unorderedBookId.add(bookshelf.get(i).getImageId());
			}
		}

		public int getCount() {
			return unorderedBookId.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView;
			if (convertView == null) { // if it's not recycled, initialize some
										// attributes
				imageView = new ImageView(mContext);
				imageView.setLayoutParams(new GridView.LayoutParams(31, 50));
				imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
				imageView.setPadding(4, 4, 4, 4);
			} else {
				imageView = (ImageView) convertView;
			}

			imageView.setImageResource(unorderedBookId.get(position));
			return imageView;
		}
	}
}